package cc.iteachyou.template.taglib.directives;

import cc.iteachyou.template.dom.VirtualDOMAttr;
import cc.iteachyou.template.dom.VirtualDOMElementNode;
import cc.iteachyou.template.dom.VirtualDOMNode;
import cc.iteachyou.template.dom.VirtualDOMTextNode;
import cc.iteachyou.template.taglib.IDirectiveHandler;
import cc.iteachyou.template.taglib.result.DirectiveResult;
import cn.hutool.core.util.IdUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class TextDirectiveHandler implements IDirectiveHandler {
    @Override
    public Optional<DirectiveResult> handler(VirtualDOMNode.RendererVirtualDOMAttrContext ctx, Map<String, Object> data) {
        VirtualDOMNode node = ctx.getNode();
        VirtualDOMAttr attr = ctx.getAttr();

        Object eval = engine.eval(attr.getValue(), data);

        if(node instanceof VirtualDOMElementNode){
            VirtualDOMElementNode element = (VirtualDOMElementNode) node;

            VirtualDOMTextNode textNode = new VirtualDOMTextNode();
            textNode.setHash(IdUtil.objectId());
            textNode.setContent(eval == null ? null : eval.toString());

            List<VirtualDOMNode> textNodes = Arrays.asList(textNode);
            element.setChildren(textNodes);
        }

        return Optional.ofNullable(null);
    }
}
